package com.example.hospitalapp;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

public class MedicalRecordAdapter extends RecyclerView.Adapter<MedicalRecordAdapter.MedicalRecordViewHolder> {

    private Context context;
    private List<MedicalRecord> medicalRecords;

    public MedicalRecordAdapter(Context context, List<MedicalRecord> medicalRecords) {
        this.context = context;
        this.medicalRecords = medicalRecords;
    }

    @Override
    public MedicalRecordViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // Inflate the item layout (item_medical_record.xml)
        View itemView = LayoutInflater.from(context).inflate(R.layout.item_medical_record, parent, false);
        return new MedicalRecordViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MedicalRecordViewHolder holder, int position) {
        MedicalRecord record = medicalRecords.get(position);

        // Set values for each item in the list
        holder.txtVisitDate.setText("就诊日期: " + record.getVisitDate());
        holder.txtDiagnosis.setText("诊断: " + record.getDiagnosis());
        holder.txtTreatment.setText("治疗: " + record.getTreatment());

        // Set "查看处方" button click listener
        holder.btnViewPrescription.setOnClickListener(view -> {
            fetchPrescription(record.getRecordId());
        });
    }

    @Override
    public int getItemCount() {
        return medicalRecords.size();
    }

    // Method to fetch prescription details based on the record ID
    private void fetchPrescription(int medicalRecordId) {
        JSONObject params = new JSONObject();
        try {
            params.put("medicalrecordId", medicalRecordId); // 传递病历 ID 查询处方
        } catch (Exception e) {
            e.printStackTrace();
        }

        ApiClient apiClient = new ApiClient(context);
        apiClient.postRequest("http://zhsj.autumnclouds.cn/prescription/query", params, new ApiClient.VolleyCallback() {
            @Override
            public void onSuccess(JSONObject response) {
                try {
                    int code = response.getInt("code");
                    if (code == 200) {
                        // 获取处方数据
                        JSONArray dataArray = response.getJSONArray("data");
                        if (dataArray.length() > 0) {
                            JSONObject prescriptionData = dataArray.getJSONObject(0);  // 假设获取第一个处方记录

                            Prescription prescription = new Prescription();
                            prescription.setPrescriptionId(prescriptionData.getInt("prescriptionId"));
                            prescription.setPatientId(prescriptionData.getInt("patientId"));
                            prescription.setDoctorId(prescriptionData.getInt("doctorId"));
                            prescription.setPrescriptionDate(prescriptionData.getString("prescriptionDate"));
                            prescription.setMedications(prescriptionData.getString("medications"));
                            prescription.setStatus(prescriptionData.getString("status"));
                            prescription.setMedicalrecordId(prescriptionData.getInt("medicalrecordId"));

                            // 解析药品信息
                            fetchMedicationsDetails(prescription);
                        } else {
                            Toast.makeText(context, "未找到处方信息", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(context, "查询处方失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(context, "查询处方失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(String error) {

            }
        });
    }

    private void fetchMedicationsDetails(Prescription prescription) {
        // 获取药品信息
        String medications = prescription.getMedications();

        // 输出原始药品信息
        Log.d("Medications", "原始药品信息: " + medications);

        // 去掉外部的大括号 {}
        medications = medications.replaceAll("[{}]", "");

        // 输出去掉大括号后的药品信息
        Log.d("Medications", "去除大括号后的药品信息: " + medications);

        // 使用逗号拆分药品信息，得到一个数组
        String[] meds = medications.split(",");

        // 输出分割后的药品条目
        Log.d("Medications", "分割后的药品条目: " + Arrays.toString(meds));

        // 确保数组长度是偶数
        if (meds.length % 2 == 0) {
            // 遍历数组，每两个元素是一组，表示一个药品的ID和数量
            for (int i = 0; i < meds.length; i += 2) {
                try {
                    // 偶数项是药品ID，奇数项是数量
                    int medicationId = Integer.parseInt(meds[i].trim()); // 药品ID
                    int quantity = Integer.parseInt(meds[i + 1].trim()); // 药品数量

                    // 输出解析后的药品 ID 和数量
                    Log.d("Medications", "药品 ID: " + medicationId + ", 数量: " + quantity);

                    // 查询药品的详细信息
                    getMedicationDetails(medicationId, quantity, prescription);
                } catch (NumberFormatException e) {
                    // 错误处理，打印错误信息
                    e.printStackTrace();
                    Log.e("Medications", "药品信息解析失败: " + meds[i] + "," + meds[i + 1]);
                    Toast.makeText(context, "药品信息解析失败: " + meds[i] + "," + meds[i + 1], Toast.LENGTH_SHORT).show();
                }
            }
        } else {
            // 如果数组长度不为偶数，说明数据格式不正确
            Log.e("Medications", "药品信息格式不正确: " + medications);
            Toast.makeText(context, "药品信息格式不正确: " + medications, Toast.LENGTH_SHORT).show();
        }
    }




    private void getMedicationDetails(int medicationId, int quantity, Prescription prescription) {
        ApiClient apiClient = new ApiClient(context);
        apiClient.getRequest("http://zhsj.autumnclouds.cn/pharmacyinventory/" + medicationId, new ApiClient.VolleyCallback() {
            @Override
            public void onSuccess(JSONObject response) {
                try {
                    int code = response.getInt("code");
                    if (code == 200) {
                        JSONObject medicationData = response.getJSONObject("data");
                        String medicationName = medicationData.getString("medicationName");
                        double price = medicationData.getDouble("price");

                        // 计算总费用
                        double totalCost = price * quantity;

                        // 将处方信息与药品详情传递到处方页面
                        Intent intent = new Intent(context, PrescriptionActivity.class);
                        intent.putExtra("prescription", prescription);
                        intent.putExtra("medicationName", medicationName);
                        intent.putExtra("quantity", quantity);
                        intent.putExtra("totalCost", totalCost);
                        context.startActivity(intent);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(context, "获取药品信息失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(String error) {

            }
        });
    }

    // ViewHolder pattern for RecyclerView
    public static class MedicalRecordViewHolder extends RecyclerView.ViewHolder {
        public TextView txtVisitDate, txtDiagnosis, txtTreatment;
        public Button btnViewPrescription;

        public MedicalRecordViewHolder(View itemView) {
            super(itemView);
            txtVisitDate = itemView.findViewById(R.id.txtVisitDate);
            txtDiagnosis = itemView.findViewById(R.id.txtDiagnosis);
            txtTreatment = itemView.findViewById(R.id.txtTreatment);
            btnViewPrescription = itemView.findViewById(R.id.btnViewPrescription);
        }
    }
}
